package com.example.homework7;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


public class SQLite extends Fragment {
    private Helper Helper;
    public SQLite() {
        super(R.layout.sqlite);
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Helper = new Helper(getContext());
        EditText e1 = getView().findViewById(R.id.textView3);
        EditText e2 = getView().findViewById(R.id.textView5);
        TextView textView = getView().findViewById(R.id.textView6);
        getView()
                .findViewById(R.id.button6)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SQLiteDatabase database = Helper.getWritableDatabase();
                        ContentValues values = new ContentValues();
                        values.put("username", e1.getText().toString());
                        values.put("age", e2.getText().toString());
                        Toast.makeText(getActivity(),
                                database.insert("users", null, values) == -1?
                                        "添加失败" : "添加成功",
                                Toast.LENGTH_SHORT).show();
                        database.close();
                        textView.setText(showDbDate(null));
                    }
                });
        getView()
                .findViewById(R.id.button7)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        textView.setText(showDbDate("age < 18"));
                    }
                });
    }
    private String showDbDate(String selection) {
        SQLiteDatabase database = Helper.getReadableDatabase();
        Cursor cursor = database.query("users",null,selection,null,null,null,null);
        StringBuilder stringBuilder = new StringBuilder();
        while(cursor.moveToNext()){
            stringBuilder
                    .append("id:")
                    .append(cursor.getLong(cursor.getColumnIndex("id")))
                    .append("    username:")
                    .append(cursor.getString(cursor.getColumnIndex("username")))
                    .append( "   age:")
                    .append(cursor.getLong(cursor.getColumnIndex("age")))
                    .append("\n");
        }
        return stringBuilder.toString();
    }
}